package httpserver

import (
	"fmt"
	corev1 "gluenet/internal/agent/api/core/v1"
	"gluenet/internal/agent/server"
	v1 "gluenet/pkg/log/v1"
	"net/http"
	"time"
)

var (
	inits = make(map[string]func(mux *http.ServeMux))
)

func registerRouter(router string, init func(mux *http.ServeMux)) {
	inits[router] = init
}

const (
	NO_SERVICE_ERRPR = "can't init service %s"
)

func InitServer(cfg *corev1.Agent) (server.Server, error) {
	services := cfg.HttpServices
	if len(services) == 0 {
		return nil, nil
	}

	if cfg.HttpAddress == `` {
		cfg.HttpAddress = `:10099`
	}

	handler := http.NewServeMux()

	for _, service := range services {

		if init, ok := inits[service]; ok {
			init(handler)
		} else {
			return nil, fmt.Errorf("invalid service: %s", service)
		}

	}

	svr := &http.Server{
		ReadTimeout:  60 * time.Second,
		WriteTimeout: 60 * time.Second,
		Handler:      handler,
		Addr:         cfg.HttpAddress,
	}

	v1.NewLogger("httpserver").Infof("listen http at: %s, service: %v", cfg.HttpAddress, services)

	return svr, nil
}
